package org.example.leetcpde;

import org.junit.jupiter.api.Test;

public class addBinary {

    @Test
    void addBinary() {
        String s = addBinary("11", "1");
        System.out.println(s);
    }

    public String addBinary(String a, String b) {
        StringBuilder builder = new StringBuilder();
        int step = 0;
        char[] chars1 = a.toCharArray(), chars2 = b.toCharArray();
        int len1 = chars1.length, len2 = chars2.length;

        for (int i = len1 - 1, j = len2 - 1; i >= 0 || j >= 0; ) {
            int v1 = i >= 0 ? chars1[i--]- '0' : 0;
            int v2 = j >= 0 ? chars2[j--]- '0' : 0;
            int sum = v1 + v2 + step;
            step = sum >> 1;
            sum = sum % 2;
            builder.append(sum);
        }

        if (step == 1) {
            builder.append("1");
        }

        return builder.reverse().toString();
    }
}
